#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import pandas as pd
import csv
import datetime
import random
import codecs


# def date_to_num(dates):
#     num_time = []
#     for date in dates:
#         date_time = datetime.datetime.strptime(date, '%Y-%m-%d')
#         num_date = date2num(date_time)
#         num_time.append(num_date)
#     return num_time

# 分列写入判断文件file是否存在，如果不存在，则新建文件并写入；若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
def dataToCsvCol(data, file, dec, isAppend=False):
    """
    判断文件file是否存在，如果不存在，则新建文件并写入；
    若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
    """
    file = os.getcwd() + file
    mode = 'w'
    if isAppend:
        mode = 'a+'
    f = codecs.open(file, mode, 'utf-8')
    f.writelines(data.split(dec))
    f.writelines("\n")
    f.close()

# 判断文件file是否存在，如果不存在，则新建文件并写入；若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
def dataToTxt(data, file, isAppend=False):
    """
    判断文件file是否存在，如果不存在，则新建文件并写入；
    若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
    """
    file = os.getcwd() + file
    mode = 'w'
    if isAppend:
        mode = 'a+'
    f = codecs.open(file, mode, 'utf-8')
    f.writelines(data+"\n")
    f.close()

def deleteFile(file):
    file = os.getcwd() + file
    if os.path.exists(file):
        if os.path.getsize(file):
            os.remove(file)


# 判断文件file是否存在，如果不存在，则新建文件并写入；若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
def dataFrameToCsv(data, file, isAppend, columns=None ,headerValue=False, headerTitle=True):
    """
    判断文件file是否存在，如果不存在，则新建文件并写入；
    若文件存在，判断文件里是否有内容，如无内容，则写入；反之，则判断是否追加
    columns 为0时，不限制列名
    :param data:
    :param file:
    :param isAppend:
    :param columns:
    :return:
    """
    file = os.getcwd() + file
    if os.path.exists(file):
        if os.path.getsize(file):
            # print('文件存在且不为空')
            if isAppend:
                # mode = 'a+' 表示在已有数据基础上添加新数据，并不覆盖已有数据,stock=False表示文件中不添加索引，header=False表示不添加列名
                if columns is not None:
                    data.to_csv(file, mode='a+', index=headerValue,  columns=columns, encoding='utf-8-sig', header=headerTitle)
                else:
                    data.to_csv(file, mode='a+', index=headerValue, encoding='utf-8-sig', header=headerTitle)
            else:
                os.remove(file)
                if columns is not None:
                    data.to_csv(file, mode='a', index=headerValue, columns=columns, encoding='utf-8-sig', header=headerTitle)
                else:
                    data.to_csv(file, mode='a', index=headerValue, encoding='utf-8-sig', header=headerTitle)
        else:
            # print('文件存在且为空')
            if columns is not None:
                data.to_csv(file, mode='a', index=headerValue, columns=columns, encoding='utf-8-sig', header=headerTitle)
            else:
                data.to_csv(file, mode='a', index=headerValue, encoding='utf-8-sig', header=headerTitle)
    else:
        print('文件不存在，重新生成')
        if columns is not None:
            data.to_csv(file, mode='a', index=headerValue, columns=columns, encoding='utf-8-sig', header=headerTitle)
        else:
            data.to_csv(file, mode='a', index=headerValue, encoding='utf-8-sig', header=headerTitle)


def getYesterday(num):
    """获取前一天日期"""
    today=datetime.date.today()
    oneday=datetime.timedelta(days=num)
    yesterday=today-oneday
    return yesterday

def getNowDate():
    return datetime.date.today()

# 计算时间差多少天
def day_count(start: str, end: str):
    """
    计算两个时期相差多少天
    :param start:'20210820'
    :param end: '20210827'
    :return: 7
    """
    old = datetime.datetime(int(start[0:4]), int(start[4:6]), int(start[6:8]))
    now = datetime.datetime(int(end[0:4]), int(end[4:6]), int(end[6:8]))
    count = (now - old).days
    print(count)
    return count


def listRandomChoice(randomlist, num):
    """
    从list随机选取num个数重新组成一个list
    :return:
    """
    return random.sample(randomlist, num)


def sumSign_fun(x):
    if x != 0:
        return 1


def csvAppendLine(input_csv, line):
    """
    往指定input_csv添加行line
    :param input_csv:
    :return:
    """
    input_csv = os.getcwd() + input_csv
    with codecs.open(input_csv, 'a+', 'utf-8') as outfile:
        # join the headers into a string with commas and add a newline
        # outfile.write(f"{','.join(header)}\n")
        outfile.write(line+ "\n")


def countMN(M, N):
    """
    从M个数据中选择N个数据有多少种选择
    :param M:
    :param N:
    :return:
    """
    result = 1
    for i in range(N):
        result = (M-i) * result
    for j in range(N):
        result = result/(j+1)

    print("#########")
    print(result)
    return int(result)


# import random
# names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
# print(random.sample(names, 5))

# print(countMN(5,2))


def strSub(data, splitStr, constr):
    """
    对字符串进行处理
    :param data:
    :param splitStr:
    :param constr:
    :return:
    """
    result = ''
    strList = data.split(splitStr)
    for str in strList:
        if str.find(constr) >0:
            result = result + " " + str
    return result


# data = ' KDJ_S_acc-KDJ_N:14, KDJ_S_acc-KDJ_M1:5, KDJ_S_acc-KDJ_M2:6, WR_S_acc-WR_N:10, WR_S_acc-WR_N1:9, WR_S_acc-WR_N2:5, MACD_S_acc-MACD_MID:11, MACD_LONG:22, MACD_S_acc-MACD_SHORT:8, MACD_S_acc-MACD_LONG2:43, MACD_S_acc-MACD_LONG3:57, BRAR_S_acc-BRAR_N:24, LB_S_acc-LB_N:3, MFI_S_acc-MFI_TimePeriod:14, MA_S_acc_MA_N:4, BOLL_S_acc-BOLL_N:12, BOLL_S_acc-BOLL_M:5, OBV_S_acc-OBV_TimePeriod:35'
#
# print(strSub(data, ',', 'KDJ_S_acc'))


def str_of_num(num):
    '''
    递归实现，精确为最大单位值 + 小数点后三位
    '''
    def strofsize(num, level):
        if level >= 2:
            return num, level
        elif num >= 10000:
            num /= 10000
            level += 1
            return strofsize(num, level)
        else:
            return num, level
    units = ['', '万', '亿']
    num, level = strofsize(num, 0)
    if level > len(units):
        level -= 1
    return '{}{}'.format(round(num, 3), units[level])
